<?php
header("Content-type: text/html; charset=utf-8");
ini_set('display_errors', 0);
set_time_limit(0);
include_once dirname(__FILE__) . '/mgtv_v2/mgtv_init.php';
include_once dirname(dirname(__FILE__)).'/np/np_http_curl.class.php';
include_once dirname(__FILE__) . '/nn_logic/vod_media/vod_media.class.php';
class ftp_download extends nn_public_return
{
    public $obj_dc = null;
    public $arr_params = null;
    
    public function __construct($dc,$arr_params=null)
    {
        $this->obj_dc = $dc;
        $this->arr_params = $arr_params;
    }
    
    /**
     * 自身消息反馈
     * @param unknown $data
     * @return string
     */
    public function self_return_data($data)
    {
        $arr=array(
            'err'=>$data['ret'],
            'status' => $data['ret'],
            'reason' => $data['reason'],
        );
        if(isset($data['data_info']) && strlen($data['data_info']) >0)
        {
            $arr['msg']['download_url'] = $data['data_info'];
        }
        return json_encode($arr);
    }
    
    /**
     * 初始化
     */
    public function init()
    {
        $file_id = $this->arr_params['file_id'];
        $this->sp_id = $this->arr_params['sp_id'];
        $this->cp_id = (isset($this->arr_params['cp_id']) && strlen($this->arr_params['cp_id']) > 0) ? $this->arr_params['cp_id'] : '';
        $arr_sp_config = $this->__get_sp_config();
        if($arr_sp_config['ret'] !=0)
        {
            return $this->self_return_data($arr_sp_config);
        }
        if(strlen($this->cp_id) > 0)
        {
            $str_cp_id_sql=" and nns_cp_id='{$this->cp_id}' ";
        }
        $str_media_id_sql = "nns_import_id='{$file_id}' ";
        $media_id = (isset($this->arr_params['media_id']) && strlen($this->arr_params['media_id']) > 0) ? $this->arr_params['media_id'] : '';
        if(strlen($media_id) > 0)
        {
            $str_media_id_sql = " nns_id='{$media_id}' ";
        }
        $sql = "select * from nns_vod_media where {$str_media_id_sql} and nns_deleted!=1 {$str_cp_id_sql} ";
        $media_info = nl_vod_media_v2::query_by_sql($this->obj_dc,$sql);
        if($media_info['ret'] !=0)
        {
            return $this->self_return_data($media_info);
        }
        if(!isset($media_info['data_info'][0]) || empty($media_info['data_info'][0]) || !is_array($media_info['data_info'][0]))
        {
            return $this->self_return_data($this->__return_data(1,'查询片源为空'));
        }
        $media_info = $media_info['data_info'][0];
        $arr_cp_config = $this->_get_cp_info($media_info['nns_cp_id']);
        if($arr_cp_config['ret'] !=0)
        {
            return $this->self_return_data($arr_cp_config);
        }
        $media_info['nns_url'] = urldecode($media_info['nns_url']);
        if(isset($media_info['nns_live_to_media']) && $media_info['nns_live_to_media'] == '1')
        {
            global $g_core_npss_url;
            $core_npss_url = $g_core_npss_url;
            unset($g_core_npss_url);
            if(strlen($core_npss_url)<1)
            {
                return $this->self_return_data(array('ret'=>1,'reason'=>'全局g_core_npss_url配置为空'));
            }
            if(strlen($media_info['nns_ext_url'])<1)
            {
                return $this->self_return_data(array('ret'=>1,'reason'=>'nns_ext_url为空'));
            }
            $arr_nns_ext_url = json_decode($media_info['nns_ext_url'],true);
            if(!isset($arr_nns_ext_url['playbill_playurls']) || empty($arr_nns_ext_url['playbill_playurls']) || !is_array($arr_nns_ext_url['playbill_playurls']))
            {
                return $this->self_return_data(array('ret'=>1,'reason'=>'nns_ext_url[playbill_playurls]为空'));
            }
            $arr_nns_ext_url = $arr_nns_ext_url['playbill_playurls'];
            if(!isset($arr_nns_ext_url['nns_content_id']) || strlen($arr_nns_ext_url['nns_content_id'])<1)
            {
                return $this->self_return_data(array('ret'=>1,'reason'=>'nns_ext_url[playbill_playurls][nns_content_id]为空'));
            }
            if(!isset($arr_nns_ext_url['start_date']) || strlen($arr_nns_ext_url['start_date'])<1)
            {
                return $this->self_return_data(array('ret'=>1,'reason'=>'nns_ext_url[playbill_playurls][start_date]为空'));
            }
            if(!isset($arr_nns_ext_url['start_time']) || strlen($arr_nns_ext_url['start_time'])<1)
            {
                return $this->self_return_data(array('ret'=>1,'reason'=>'nns_ext_url[playbill_playurls][start_time]为空'));
            }
            if(!isset($arr_nns_ext_url['duration']) || strlen($arr_nns_ext_url['duration'])<1)
            {
                return $this->self_return_data(array('ret'=>1,'reason'=>'nns_ext_url[playbill_playurls][duration]为空'));
            }
            if(!isset($arr_nns_ext_url['timezone']) || strlen($arr_nns_ext_url['timezone'])<1)
            {
                return $this->self_return_data(array('ret'=>1,'reason'=>'nns_ext_url[playbill_playurls][timezone]为空'));
            }
            $media_info['nns_url'] = "http://{$core_npss_url}/nl.ts?id={$arr_nns_ext_url['nns_content_id']}&nn_day=".date("Ymd",strtotime($arr_nns_ext_url['start_date'])).
            "&nn_begin=".date("His",strtotime($arr_nns_ext_url['start_time']))."&nn_time_len={$arr_nns_ext_url['duration']}&nn_timezone={$arr_nns_ext_url['timezone']}";
            $media_info['nns_url'] = urlencode($media_info['nns_url']);
        }
        else
        {
            if(isset($this->arr_cp_config[$media_info['nns_cp_id']]['nns_config']['down_url_real']) && strlen($this->arr_cp_config[$media_info['nns_cp_id']]['nns_config']['down_url_real'])>0)
            {
                $down_url_real = rtrim($this->arr_cp_config[$media_info['nns_cp_id']]['nns_config']['down_url_real'],'/');
                if(stripos($media_info['nns_url'], 'http://') === FALSE && stripos($media_info['nns_url'], 'ftp://') === FALSE)
                {
                    $media_info['nns_url'] = $down_url_real.'/'.ltrim($media_info['nns_url'],'/');
                }
            }
            if (!isset($this->arr_cp_config[$media_info['nns_cp_id']]['nns_config']['down_method_ftp_illegal_character']) || !in_array($this->arr_cp_config[$media_info['nns_cp_id']]['nns_config']['down_method_ftp_illegal_character'], array('1','2')))
            {
                $media_info['nns_url'] = $this->clean_illegal_character($media_info['nns_url']);
            }
            else if(isset($this->arr_cp_config[$media_info['nns_cp_id']]['nns_config']['down_method_ftp_illegal_character']) && $this->arr_cp_config[$media_info['nns_cp_id']]['nns_config']['down_method_ftp_illegal_character'] == '2')
            {
                $media_info['nns_url'] = $this->utf8_to_gbk_and_encode($media_info['nns_url']);
            }
            if ($this->arr_cp_config[$media_info['nns_cp_id']]['nns_config']['down_method'] != '0')
            {
                $down_method_ftp = $this->arr_cp_config[$media_info['nns_cp_id']]['nns_config']['down_method_ftp'];
                $pasv = ($down_method_ftp==0) ? true : false;
            }
        }
        return $this->self_return_data($this->__return_right_data($media_info['nns_url']));
    }
    
    /**
     * ftp 验证文件是否存在
     * @param unknown $url url地址
     * @param unknown $pasv 主被动模式
     */
    private function check_ftp_file($url,$pasv)
    {
        $url_arr = parse_url($url);
        $port = isset($url_arr["port"]) ? $url_arr["port"] : 21;
        $time = 10;
        $connect_no = @ftp_connect($url_arr['host'], $port, $time);
        if ($connect_no === FALSE)
        {
            return FALSE;
        }
        @ftp_login($connect_no, $url_arr["user"], $url_arr["pass"]);
        //吉林联通要开启被动模式
        @ftp_pasv($connect_no, $pasv);
        $contents = @ftp_nlist($connect_no, $url_arr['path']);
        if ($contents === false)
        {
            return FALSE;
        }
        if (empty($contents))
        {
            return FALSE;
        }
        return true;
    }
    
    /**
     * url地址中文 编码转换
     * @param unknown $url
     */
    private function utf8_to_gbk_and_encode($url,$charset='GBK')
    {
        $temp_server_url = parse_url($url);
        $temp_child_val = '';
        if(isset($temp_server_url['scheme']) && strlen($temp_server_url['scheme'])>0)
        {
            $temp_child_val.=$temp_server_url['scheme']."://";
        }
        if(isset($temp_server_url['user']) && strlen($temp_server_url['user'])>0 && isset($temp_server_url['pass']) && strlen($temp_server_url['pass'])>0)
        {
            $temp_child_val.=$temp_server_url['user'].":".$temp_server_url['pass']."@";
        }
        if(isset($temp_server_url['host']) && strlen($temp_server_url['host'])>0)
        {
            $temp_child_val.=$temp_server_url['host'];
        }
        if(isset($temp_server_url['port']) && strlen($temp_server_url['port'])>0)
        {
            $temp_child_val.=":".$temp_server_url['port'];
        }
        if(isset($temp_server_url['path']) && strlen($temp_server_url['path'])>0)
        {
            $arr_path = explode('/', $temp_server_url['path']);
            $arr_path = array_filter($arr_path);
            if(is_array($arr_path) && !empty($arr_path))
            {
                foreach ($arr_path as $key_path=>$val_path)
                {
                    if (preg_match("/[\x7f-\xff]/", $val_path))
                    {
                        $arr_path[$key_path] = rawurlencode(iconv(mb_detect_encoding($val_path), $charset,$val_path ));
                    }
                }
                $temp_server_url['path'] = '/'.implode('/', $arr_path);
            }
            $temp_child_val.=$temp_server_url['path'];
        }
        if(isset($temp_server_url['query']) && strlen($temp_server_url['query'])>0)
        {
            $temp_child_val.='?'.$temp_server_url['query'];
        }
        return $temp_child_val;
    }
    
    /**
     * 中文符号转换（贵州使用）
     */
    private function clean_illegal_character($url)
    {
        if(stripos($url, "：") !== false)
        {
            $url = str_replace("：", "%A3%BA", $url);
        }
        if(stripos($url, "？") !== false)
        {
            $url = str_replace("？", "%A3%BF", $url);
        }
        if(stripos($url, "“") !== false)
        {
            $url = str_replace("“", "%A1%B0", $url);
        }
        if(stripos($url, "”") !== false)
        {
            $url = str_replace("”", "%A1%B1", $url);
        }
        if(stripos($url, "！") !== false)
        {
            $url = str_replace("！", "%A3%A1", $url);
        }
        if(stripos($url, "。") !== false)
        {
            $url = str_replace("。", "%A1%A3", $url);
        }
        if(stripos($url, "，") !== false)
        {
            $url = str_replace("，", "%A3%AC", $url);
        }
        if(stripos($url, "、") !== false)
        {
            $url = str_replace("、", "%A1%A2", $url);
        }
        if(stripos($url, " ") !== false)
        {
            $url = str_replace(" ", "%20", $url);
        }
        if(stripos($url, "（") !== false)
        {
            $url = str_replace("（", "%A3%A8", $url);
        }
        if(stripos($url, "）") !== false)
        {
            $url = str_replace("）", "%A3%A9", $url);
        }
        if(stripos($url, "；") !== false)
        {
            $url = str_replace("；", "%A3%BB", $url);
        }
        if(stripos($url, "《") !== false)
        {
            $url = str_replace("《", "%A1%B6", $url);
        }
        if(stripos($url, "》") !== false)
        {
            $url = str_replace("》", "%A1%B7", $url);
        }
        if(stripos($url, "·") !== false)
        {
            $url = str_replace("·", "%A1%A4", $url);
        }
        if(stripos($url, "—") !== false)
        {
            $url = str_replace("—", "%A1%AA", $url);
        }
        return $url;
    }
}
$dc = nl_get_dc(array (
    'db_policy' => NL_DB_WRITE,
    'cache_policy' => NP_KV_CACHE_TYPE_NULL
));
$obj_ftp_download = new ftp_download($dc,$_GET);
echo $obj_ftp_download->init();